// pages/merchantsCertification/merchantsCertification.js
const host = require('../../config.js').host;
const network = require('../../utils/network.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: host,
    canEditFlg: true,
    storePhotoList: [],
    tradingCertificateList: [],
    formData:{},
    address: {}
  },

  nameInput(e) {
    let formData = this.data.formData;
    formData.name = e.detail.value;
    this.setData({
      formData: formData
    })
  },

  detailInput(e) {
    let formData = this.data.formData;
    formData.detail = e.detail.value;
    this.setData({
      formData: formData
    })
  },

  chooseStorePhotos() {
    let that = this;
    let formData = this.data.formData;
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      success: function (res) {
        network.uploadFileLoading("/common/upload", res.tempFiles[0].path, res => {
          let data = JSON.parse(res.data);
          let servicePath = data.fileName;
          let imgUrl = host + servicePath;
          formData.storePhotos = servicePath;
          that.setData({
            formData: formData,
            storePhotoList: [imgUrl]
          })
        })
      }
    });
  },

  chooseTradingCertificate() {
    let that = this;
    let formData = this.data.formData;
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      success: function (res) {
        network.uploadFileLoading("/common/upload", res.tempFiles[0].path, res => {
          let data = JSON.parse(res.data);
          let servicePath = data.fileName;
          let imgUrl = host + servicePath;
          formData.tradingCertificate = servicePath;
          that.setData({
            formData: formData,
            tradingCertificateList: [imgUrl]
          })
        })
      }
    });
  },

  viewStorePhoto(e) {
    wx.previewImage({
      urls: this.data.storePhotoList,
      current: e.currentTarget.dataset.url
    });
  },

  viewTradingCertificate(e) {
    wx.previewImage({
      urls: this.data.tradingCertificateList,
      current: e.currentTarget.dataset.url
    });
  },

  DelImg(e) {
    let type = e.currentTarget.dataset.type;
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          if(type == 1){
            let imgList = this.data.storePhotoList;
            imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              storePhotoList: imgList
            })
          }
          if(type == 2){
            let imgList = this.data.tradingCertificateList;
            imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              tradingCertificateList: imgList
            })
          }
        }
      }
    })
  },

  /**
   * 获取用户认证信息
   */
  getCustomerAuth() {
    let address = this.data.address;
    network.requestGet('/xcx/customer/getCustomerAuth', {}, res => {
      if(res.data.data){
        let retData = res.data.data;
        address.id = retData.addressId;
        let storePhotos = host + retData.storePhotos;
        let tradingCertificate = host + retData.tradingCertificate;
        this.setData({
          formData: retData,
          address: address,
          canEditFlg: retData.auditState == 1?false:true,
          storePhotoList: [storePhotos],
          tradingCertificateList: [tradingCertificate]
        })
        if(retData.auditState == 0){
          wx.showModal({
            title: '提示',
            content: '审核中，请耐心等待审核',
            showCancel: false,
            confirmText: '返回',
            success: res => {
              if (res.confirm) {
                wx.navigateBack();
              }
            }
          })
        }
      } else {
        this.getCustomerAuthAddress();
      }
    })
  },


  chooseAddressTap() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: res => {
        this.chooseAddress()
      },
      fail: res => {
        wx.showModal({
          title: '提示',
          content: '若不授权，将无法使用地理位置功能',
          cancelText: '不授权',
          cancelColor: '#999',
          confirmText: '授权',
          confirmColor: '#f94218',
          success: res => {
            if (res.confirm) {
              wx.openSetting({
                success: res => {
                  if (res.authSetting["scope.userLocation"]) { //如果用户重新同意了授权登录scope.userLocation是表示位置授权 true/false
                    this.chooseAddress()
                  }
                }
              })
            }
          }
        })
      }
    })
  },
  /**
   * 选择地址
   */
  chooseAddress(e) {
    let address = this.data.address;
    let formData = this.data.formData;
    let that = this;
    wx.chooseLocation({
      success: res => {
        formData.addressDetail = res.address;
        address.name = res.name;
        address.detail = res.address;
        address.latitude = res.latitude;
        address.longitude = res.longitude;
        address.addressType = 0;
        address.ownerType = 1;
        //新增或修改认证地址
        if(formData.addressId){
          network.requestPost('/xcx/deviceAddress/editDeviceAddress', address, res => {
            if(res.data.code == '200'){
              that.setData({
                address: address,
                formData: formData
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          })
        } else {
          network.requestPost('/xcx/deviceAddress/addAddress', address, res => {
            if(res.data.code == '200'){
              formData.addressId = res.data.data;
              address.id = res.data.data;
              that.setData({
                address: address,
                formData: formData
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          })
        }

      }
    })
  },

  /**
   * 提交审核
   */
  addCustomerAuth() {
    let formData = this.data.formData;
    let address = this.data.address;
    if(!formData.name){
      wx.showToast({
        title: '请输入商家名称',
        icon: 'none'
      })
      return false;
    }
    if(!formData.storePhotos){
      wx.showToast({
        title: '请上传商家logo',
        icon: 'none'
      })
      return false;
    }
    if(!formData.tradingCertificate){
      wx.showToast({
        title: '请上传营业证书',
        icon: 'none'
      })
      return false;
    }
    if(!formData.addressId || !formData.addressDetail || !address.id){
      wx.showToast({
        title: '请选择商家地址',
        icon: 'none'
      })
      return false;
    }
    network.requestPost('/xcx/customer/addCustomerAuth', formData, res => {
      if(res.data.code == '200'){
        wx.showToast({
          title: '成功提交审核，请耐心等待审核',
          icon: 'none'
        })
        setTimeout(function () {
         wx.navigateBack({
           delta: 1,
         })
        }, 800)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 重新认证
   */
  againCustomerAuth() {
    let formData = this.data.formData;
    let address = this.data.address;
    if(!formData.name){
      wx.showToast({
        title: '请输入商家名称',
        icon: 'none'
      })
      return false;
    }
    if(!formData.storePhotos){
      wx.showToast({
        title: '请上传商家logo',
        icon: 'none'
      })
      return false;
    }
    if(!formData.tradingCertificate){
      wx.showToast({
        title: '请上传营业证书',
        icon: 'none'
      })
      return false;
    }
    if(!formData.addressId || !formData.addressDetail || !address.id){
      wx.showToast({
        title: '请选择商家地址',
        icon: 'none'
      })
      return false;
    }
    formData.auditState = 0;
    network.requestPost('/xcx/customer/againCustomerAuth', formData, res => {
      if(res.data.code == '200'){
        wx.showToast({
          title: '成功提交审核，请耐心等待审核',
          icon: 'none'
        })
        setTimeout(function () {
         wx.navigateBack({
           delta: 1,
         })
        }, 800)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  getCustomerAuthAddress(){
    let formData = this.data.formData;
    let address = this.data.address;
    network.requestGet('/xcx/deviceAddress/getCustomerAuthAddress', {}, res => {
      if(res.data.code == '200'){
        if(res.data.data){
          formData.addressId = res.data.data.id;
          formData.addressDetail = res.data.data.detail;
          address.id = res.data.data.id;
          this.setData({
            address: address,
            formData: formData
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCustomerAuth();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})